using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

public partial class Pages_Employee_ManageCustomers_EditCustomer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["id"] != null)
                FillFields();
            else
                Response.Redirect("ViewCustomers.aspx");
        }
    }

    /// <summary>
    /// Fills the fields with information of the customer object with ID on the query string
    /// </summary>
    private void FillFields()
    {
        try {
            int id = Int32.Parse(Request.QueryString["id"].ToString());
            List<Customer> list = DALCustomers.GetCustomersByID(id);
            if (list.Count < 1)
                Response.Redirect("~/Errors/ConnectionError.aspx");
            Customer customer = list[0];
            txtCustomerID.Text = customer.CustomerID.ToString();
            txtContactNumber.Text = customer.ContactNumber;
            txtFullName.Text = customer.FullName;
            txtAddress.Text = customer.Address;
            txtEmail.Text = customer.Email;
            txtPhoneNumber.Text = customer.PhoneNumber;
        }
        catch (FormatException ex)
        {
            Response.Redirect("~/Errors/GeneralError.aspx");
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid) return;

        int id = Int32.Parse(txtCustomerID.Text);
        string contactNumber = txtContactNumber.Text;
        string fullName = txtFullName.Text.Trim();
        string address = txtAddress.Text.Trim();
        string email = txtEmail.Text.Trim();
        string phoneNumber = txtPhoneNumber.Text.Trim();

        int affected;
        try
        {
            affected = DALCustomers.UpdateCustomer(id, contactNumber, fullName, address, email, phoneNumber);
            if (affected > 0)
                lblMessage.Text = "Edited successfully";
            else
                lblMessage.Text = "Error editing customer";
        }
        catch
        {
            lblMessage.Text = "Error editing customer";
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        // Reset all fields to original values
        FillFields();
        lblMessage.Text = "";
        txtFullName.Focus();
    }

    protected void btnRegenerate_Click(object sender, EventArgs e)
    {
        // Regenerate a new random contact number
        txtContactNumber.Text = StringGenerator.GetContactNumber();
    }
}
